#include "stdio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "freertos/timers.h"

#include "iot_button.h"
#include "esp_system.h"
#include "esp_log.h"


#include <esp_pm.h>
#include <esp_sleep.h>

#include "Trace.h"

#include "PowerManager.h"
#include "./uart/uartintf.h"

#define CONFIG_EXAMPLE_MAX_CPU_FREQ_MHZ 80
#define CONFIG_EXAMPLE_MIN_CPU_FREQ_MHZ 10

void PowerManager::close_led(gpio_num_t gpio_num){
    open_led(gpio_num);
    gpio_set_level(gpio_num, 0);
    gpio_config_t gpio_config_structure;
    gpio_config_structure.pin_bit_mask = (1ULL << gpio_num);/* 閫夋嫨gpio2 */
    gpio_config_structure.mode = GPIO_MODE_DISABLE;              /* 杈撳嚭妯″紡 */
    gpio_config_structure.pull_up_en = GPIO_PULLUP_DISABLE;                       /* 涓嶄笂鎷� */
    gpio_config_structure.pull_down_en = GPIO_PULLDOWN_DISABLE;                     /* 涓嶄笅鎷� */
    gpio_config_structure.intr_type = GPIO_INTR_DISABLE;    /* 绂佹涓柇 */

    /* 鏍规嵁璁惧畾鍙傛暟鍒濆鍖栧苟浣胯兘 */
    gpio_set_direction(gpio_num, GPIO_MODE_OUTPUT);
    gpio_set_level(gpio_num, 0);
    gpio_config(&gpio_config_structure);
}

void PowerManager::open_led(gpio_num_t gpio_num){
    gpio_set_level(gpio_num, 0);
    gpio_config_t gpio_config_structure;
    gpio_config_structure.pin_bit_mask = (1ULL << gpio_num);/* 閫夋嫨gpio2 */
    gpio_config_structure.mode = GPIO_MODE_OUTPUT;              /* 杈撳嚭妯″紡 */
    gpio_config_structure.pull_up_en = GPIO_PULLUP_DISABLE;                       /* 涓嶄笂鎷� */
    gpio_config_structure.pull_down_en = GPIO_PULLDOWN_DISABLE;                     /* 涓嶄笅鎷� */
    gpio_config_structure.intr_type = GPIO_INTR_DISABLE;    /* 绂佹涓柇 */

    gpio_set_level(gpio_num, 1);
    gpio_config(&gpio_config_structure);
}


PowerManager::PowerManager()
{
}

PowerManager::~PowerManager()
{
}

int PowerManager::enableLightSleep() {
    TRACE_B();
    // goto Light-sleep
    esp_pm_config_esp32c3_t pmcfg;
    pmcfg.max_freq_mhz = CONFIG_EXAMPLE_MAX_CPU_FREQ_MHZ;
    pmcfg.min_freq_mhz = CONFIG_EXAMPLE_MIN_CPU_FREQ_MHZ;
    pmcfg.light_sleep_enable = true;
    esp_err_t ret = esp_pm_configure(&pmcfg); //自动 Light-sleep
    LOGI("%s esp_pm_configure ret0:0x%x", __func__, ret);
    // return 0;
    // close uart
    // UartIntf::closeUarts();

    // close led
    for (int i = 0; i< GPIO_NUM_MAX; i++) {
        if (i != GPIO_NUM_3 //skip GPIO3 for Lock Motor
        && i < GPIO_NUM_11
        && i != GPIO_NUM_9) {
            LOGI("%s close ret:0x%x", __func__, i);
            close_led((gpio_num_t)i);
        }

    }
    close_led(GPIO_NUM_18);
    close_led(GPIO_NUM_19);
    close_led(GPIO_NUM_20);
    close_led(GPIO_NUM_21);

    // close bt/wifi
    // esp_bluedroid_disable();
    // esp_bt_controller_disable();
    // esp_wifi_stop();
    // esp_light_sleep_start();
    return 0;
}
